#pragma once
#include <string>
#include <curl/curl.h>
#include <unordered_map>

namespace CppWinApi::HttpClients
{
    class FormUrlEncodedContent
    {
    public:
        static std::string ToString(std::unordered_map<std::string, std::string> keyValues)
        {
            std::string data = "";

            if (keyValues.empty())
            {
                return data;
            }

            auto it = keyValues.begin();
            auto keyStr = ::curl_easy_escape(nullptr, it->first.c_str(), it->first.length());
            auto valueStr = ::curl_easy_escape(nullptr, it->second.c_str(), it->second.length());
            data.append(std::string(keyStr) + "=" + valueStr);
            ::curl_free(keyStr);
            ::curl_free(valueStr);
            ++it;

            // 使用迭代器遍历
            for (; it != keyValues.end(); ++it)
            {
                keyStr = ::curl_easy_escape(nullptr, it->first.c_str(), it->first.length());
                valueStr = ::curl_easy_escape(nullptr, it->second.c_str(), it->second.length());
                data.append(std::string("&") + keyStr + "=" + valueStr);
                ::curl_free(keyStr);
                ::curl_free(valueStr);
            }

            return data;
        }
    };
}